package com.vmj.classfile;

import com.vmj.Command;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by yangshoujun on 2017/8/20 上午12:23.
 */
public class DirectoryClassLoader implements ClassLoader {

    private Command command;

    public DirectoryClassLoader(Command cmd) {
        this.command = cmd;
    }

    public byte[] loadClass(String className) throws IOException {
        String classpath = command.getClasspath();
        String newClassName = className.replace('.', File.separatorChar);
        String absPath = classpath + File.separator + newClassName + ".class";
        File file = new File(absPath);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fins = null;
        fins = new FileInputStream(file);
        byte[] buf = new byte[1024];
        int read;
        while( (read = fins.read(buf)) != -1) {
            baos.write(buf, 0, read);
        }
        return baos.toByteArray();
    }
}
